package com.leap.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.ChatRecord;
import com.leap.entity.Message;
import com.leap.mapper.ChatRecordMapper;
import com.leap.service.ChatRecordService;
import com.leap.utils.Const;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper,ChatRecord> implements ChatRecordService {
    @Override
    public List<Message> initMessages() {
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("system", Const.KIMI_INIT));
        return messages;
    }

    @Override
    public void saveMessages(Long accountId, List<Message> messageList,int num,String title) {
        String jsonString = JSON.toJSONString(messageList);
        LambdaUpdateWrapper<ChatRecord> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatRecord::getAccountId, accountId);
        wrapper.eq(ChatRecord::getNum, num);
        wrapper.set(ChatRecord::getAccountId, accountId);
        wrapper.set(ChatRecord::getMessage, jsonString);
        if (!title.isEmpty()) {
            wrapper.set(ChatRecord::getTitle, title);
        }

        if(!this.update(wrapper)){
            List<ChatRecord> chatSumByAccountId = this.getChatSumByAccountId(accountId);
            int size = chatSumByAccountId.size();
            ChatRecord chatRecord = ChatRecord.builder()
                    .accountId(accountId)
                    .num(size+1)
                    .title(title.isEmpty()?"":title)
                    .message(jsonString)
                    .build();
            this.save(chatRecord);
        }
    }

    @Override
    public void updateTitle(Long accountId, Long chatId, String title) {
        LambdaUpdateWrapper<ChatRecord> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatRecord::getAccountId, accountId);
        wrapper.eq(ChatRecord::getId,chatId);
        wrapper.set(ChatRecord::getTitle, title);

        this.update(wrapper);
    }

    public List<ChatRecord> getChatSumByAccountId(Long accountId) {
        LambdaQueryWrapper<ChatRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatRecord::getAccountId, accountId);
        queryWrapper.orderByDesc(ChatRecord::getUpdateTime);
        List<ChatRecord> list = this.list(queryWrapper);
        return list;
    }
}
